package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"
	. "service/goods_srv/global"
	"service/goods_srv/model"
	"service/goods_srv/proto"
)

// 获取品牌列表
func (g *GoodsServer) BrandList(c context.Context, req *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {
	var brands []*model.Brands
	result := DB.Scopes(Paginate(int(req.Pages), int(req.PagePerNums))).Find(&brands)
	if result.Error != nil {
		return nil, result.Error
	}

	var resData []*proto.BrandInfoResponse
	for _, user := range brands {
		resData = append(resData, &proto.BrandInfoResponse{
			Id:   user.ID,
			Name: user.Name,
			Logo: user.Logo,
		})
	}
	return &proto.BrandListResponse{
		Total: int32(result.RowsAffected),
		Data:  resData,
	}, nil
}

// 添加品牌
func (g *GoodsServer) CreateBrand(c context.Context, r *proto.BrandRequest) (*proto.BrandInfoResponse, error) {
	brand := new(model.Brands)
	result := DB.Where(&model.Brands{Name: r.Name}).First(brand)
	if result.RowsAffected == 1 {
		return nil, status.Errorf(codes.AlreadyExists, "品牌已存在")
	}

	brand = &model.Brands{
		Name: r.Name,
		Logo: r.Logo,
	}
	result = DB.Create(brand)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &proto.BrandInfoResponse{
		Id:   brand.ID,
		Name: brand.Name,
		Logo: brand.Logo,
	}, nil
}

// 更新品牌
func (g *GoodsServer) UpdateBrand(c context.Context, r *proto.BrandRequest) (*emptypb.Empty, error) {
	brand := new(model.Brands)
	brand.ID = r.Id

	result := DB.Where(brand).First(brand)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在")
	}

	// 请求参数中包含零值字段也要更新
	result = DB.Model(brand).Updates(map[string]interface{}{
		"name": r.Name,
		"logo": r.Logo,
	})
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}

// 删除品牌（软删除）
func (g *GoodsServer) DeleteBrand(c context.Context, r *proto.BrandRequest) (*emptypb.Empty, error) {
	brand := new(model.Brands)
	brand.ID = r.Id

	result := DB.Where(brand).First(brand)
	if result.RowsAffected != 1 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在")
	}

	// 请求参数中包含零值字段也要更新
	result = DB.Delete(&brand)
	if result.Error != nil {
		return nil, status.Errorf(codes.Internal, result.Error.Error())
	}
	return &empty.Empty{}, nil
}

// 优雅实现分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
